<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生首页 - 局域网视频学习系统</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .student-header {
            background: linear-gradient(135deg, #FFE66D 0%, #FFA726 100%);
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            color: white;
        }

        .welcome-text {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 8px;
        }

        .welcome-subtitle {
            font-size: 14px;
            opacity: 0.9;
        }

        .search-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .search-box {
            position: relative;
            max-width: 600px;
            margin: 0 auto;
        }

        .search-input {
            width: 100%;
            padding: 12px 50px 12px 16px;
            border: 2px solid var(--border-color);
            border-radius: 25px;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: var(--student-color);
            box-shadow: 0 0 0 3px rgba(255, 230, 109, 0.2);
        }

        .search-icon {
            position: absolute;
            right: 80px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
            font-size: 18px;
        }

        .search-btn {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .search-btn:hover {
            background: #1e5f7a;
        }

        .search-tips {
            margin-top: 16px;
            text-align: center;
        }

        .search-tip {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-bottom: 12px;
            color: #666;
            font-size: 14px;
        }

        .tip-icon {
            font-size: 16px;
        }

        .search-examples {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .example-label {
            color: #666;
            font-size: 14px;
        }

        .example-item {
            background: #f0f0f0;
            color: var(--primary-color);
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .example-item:hover {
            background: var(--primary-color);
            color: white;
        }

        .categories-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .section-title {
            font-size: 18px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin-bottom: 16px;
        }

        .categories-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 15px;
        }


        .content-layout {
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 20px;
        }

        .main-content {
            min-height: 400px;
        }

        .sidebar-content {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            padding: 20px;
            height: fit-content;
            position: sticky;
            top: 20px;
        }

        .recommendations {
            margin-bottom: 30px;
        }

        .recommendation-item {
            display: flex;
            gap: 12px;
            margin-bottom: 15px;
            padding: 12px;
            border-radius: 6px;
            transition: background 0.3s ease;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
        }

        .recommendation-item:hover {
            background: rgba(255, 230, 109, 0.1);
        }

        .recommendation-thumbnail {
            width: 60px;
            height: 40px;
            background: #f0f0f0;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 16px;
            flex-shrink: 0;
        }

        .recommendation-info h4 {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 4px;
            color: var(--neutral-dark);
            line-height: 1.3;
        }

        .recommendation-meta {
            font-size: 12px;
            color: #666;
        }

        .videos-section {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            padding: 20px;
        }

        .videos-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
        }

        .video-card {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
            transition: transform 0.3s ease;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
        }

        .video-card:hover {
            transform: translateY(-2px);
        }

        .video-thumbnail {
            width: 100%;
            height: 160px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 40px;
            position: relative;
        }

        .video-duration {
            position: absolute;
            bottom: 8px;
            right: 8px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
        }

        .video-info {
            padding: 16px;
        }

        .video-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--neutral-dark);
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .video-meta {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }

        .video-stats {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 8px;
        }

        .video-views {
            font-size: 12px;
            color: #666;
        }

        .favorite-btn {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #ccc;
            transition: color 0.3s ease;
        }

        .favorite-btn:hover,
        .favorite-btn.favorited {
            color: #ff6b6b;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            color: #ccc;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        @media (max-width: 1024px) {
            .content-layout {
                grid-template-columns: 1fr;
            }
            
            .sidebar-content {
                position: static;
            }
        }

        @media (max-width: 768px) {
            .categories-grid {
                grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            }
            
            .videos-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <div class="container-fluid">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <a href="index.html" class="navbar-brand">
                    📚 局域网视频学习系统
                </a>
                <div style="display: flex; align-items: center; gap: 20px;">
                    <a href="index.html" style="color: var(--neutral-dark); text-decoration: none;">
                        🏠 首页
                    </a>
                    <a href="favorites.html" style="color: var(--neutral-dark); text-decoration: none;">
                        ❤️ 我的收藏
                    </a>
                    <a href="playlists.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📋 播放列表
                    </a>
                    <a href="exams.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📝 考试中心
                    </a>
                    <a href="profile.html" style="color: var(--neutral-dark); text-decoration: none;">
                        👤 个人资料
                    </a>
                    <span style="color: var(--neutral-dark);">
                        <span data-user-name>学生</span>
                    </span>
                    <button onclick="logout()" class="logout-btn">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="content-wrapper">
        <!-- 欢迎区域 -->
        <div class="student-header">
            <h1 class="welcome-text">欢迎回来，<span data-user-name>同学</span>！</h1>
            <p class="welcome-subtitle">今天是 <span id="currentDate"></span>，开始您的学习之旅吧</p>
        </div>

        <!-- 搜索区域 -->
        <div class="search-section">
            <div class="search-box">
                <input type="text" class="search-input" id="searchInput" placeholder="搜索视频标题、简介、标签、上传者...">
                <i class="search-icon">🔍</i>
                <button class="search-btn" onclick="performSmartSearch()">搜索</button>
            </div>
            
            <!-- 搜索提示 -->
            <div class="search-tips">
                <div class="search-tip">
                    <span class="tip-icon">💡</span>
                    <span class="tip-text">支持搜索：视频标题、简介内容、标签关键词、上传者姓名</span>
                </div>
                <div class="search-examples">
                    <span class="example-label">搜索示例：</span>
                    <span class="example-item" onclick="searchExample('Java基础')">Java基础</span>
                    <span class="example-item" onclick="searchExample('张老师')">张老师</span>
                    <span class="example-item" onclick="searchExample('编程')">编程</span>
                </div>
            </div>
        </div>


        <!-- 内容布局 -->
        <div class="content-layout">
            <!-- 主要内容区 -->
            <div class="main-content">
                <div class="videos-section">
                    <h3 class="section-title">推荐视频</h3>
                    <div class="videos-grid" id="videosGrid">
                        <div class="loading">
                            <div class="loading"></div>
                            加载中...
                        </div>
                    </div>
                </div>
            </div>

            <!-- 侧边栏 -->
            <div class="sidebar-content">
                <div class="recommendations">
                    <h4 class="section-title">为你推荐</h4>
                    <div id="recommendationsList">
                        <div class="empty-state">
                            <i>🎯</i>
                            <p>暂无推荐</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentVideos = [];
        let filteredVideos = [];
        let searchTerm = '';
        let isSmartSearch = false;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查权限
            if (!UserManager.hasPermission(2)) {
                Message.error('权限不足');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 2000);
                return;
            }

            // 设置当前日期
            const now = new Date();
            const dateStr = now.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            });
            document.getElementById('currentDate').textContent = dateStr;

            // 初始化事件监听
            initEventListeners();
            
            // 加载数据
            loadVideos();
            loadRecommendations();
        });

        // 初始化事件监听
        function initEventListeners() {
            // 搜索功能
            document.getElementById('searchInput').addEventListener('input', 
                Utils.debounce(function() {
                    searchTerm = this.value.toLowerCase();
                    if (!isSmartSearch) {
                        filterVideos();
                    }
                }, 300)
            );

            // 回车搜索
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSmartSearch();
                }
            });
        }

        // 加载视频数据
        async function loadVideos() {
            try {
                console.log('开始加载视频数据...');
                const response = await API.get('/video/all');
                console.log('视频API响应:', response);
                
                if (response.success) {
                    currentVideos = response.videos;
                    filteredVideos = [...currentVideos];
                    console.log(`成功加载 ${currentVideos.length} 个视频`);
                    
                    if (currentVideos.length === 0) {
                        console.log('没有找到视频，显示空状态');
                    }
                    
                    renderVideos();
                } else {
                    console.error('视频API返回失败:', response.message);
                    showEmptyState('加载视频失败: ' + (response.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载视频失败:', error);
                showEmptyState('网络错误，请稍后重试');
            }
        }


        // 加载推荐内容
        async function loadRecommendations() {
            try {
                // 这里可以根据用户的学习历史来推荐视频
                // 暂时显示最新的几个视频作为推荐
                const container = document.getElementById('recommendationsList');
                
                if (currentVideos.length > 0) {
                    const recommendations = currentVideos.slice(0, 3);
                    container.innerHTML = recommendations.map(video => `
                        <a href="player.html?id=${video.id}" class="recommendation-item">
                            <div class="recommendation-thumbnail">🎬</div>
                            <div class="recommendation-info">
                                <h4>${video.title}</h4>
                                <div class="recommendation-meta">${video.uploaderName || '未知老师'}</div>
                            </div>
                        </a>
                    `).join('');
                } else {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i>🎯</i>
                            <p>暂无推荐</p>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('加载推荐失败:', error);
            }
        }

        // 筛选视频
        function filterVideos() {
            if (isSmartSearch) {
                // 智能搜索模式下不进行本地筛选
                return;
            }
            
            filteredVideos = currentVideos.filter(video => {
                
                // 搜索筛选
                if (searchTerm) {
                    const searchFields = [video.title, video.intro, video.tags, video.uploaderName].filter(Boolean);
                    if (!searchFields.some(field => field.toLowerCase().includes(searchTerm))) {
                        return false;
                    }
                }
                
                return true;
            });
            
            renderVideos();
        }

        // 执行智能搜索
        async function performSmartSearch() {
            const keyword = document.getElementById('searchInput').value.trim();
            
            if (!keyword) {
                // 如果搜索框为空，恢复显示所有视频
                isSmartSearch = false;
                loadVideos();
                return;
            }
            
            try {
                isSmartSearch = true;
                
                // 使用后端的高级搜索API，将所有搜索条件都设为同一个关键词
                const response = await API.post('/video/advanced-search', {
                    title: keyword,
                    uploader: keyword,
                    tags: keyword,
                    intro: keyword
                });
                
                if (response.success) {
                    filteredVideos = response.videos || [];
                    renderVideos();
                    Message.success(`找到 ${filteredVideos.length} 个相关视频`);
                } else {
                    Message.error(response.message);
                }
            } catch (error) {
                console.error('智能搜索失败:', error);
                Message.error('搜索失败，请稍后重试');
            }
        }

        // 搜索示例点击
        function searchExample(keyword) {
            document.getElementById('searchInput').value = keyword;
            performSmartSearch();
        }

        // 渲染视频
        function renderVideos() {
            const container = document.getElementById('videosGrid');
            
            if (filteredVideos.length === 0) {
                showEmptyState('暂无相关视频');
                return;
            }
            
            container.innerHTML = filteredVideos.map(video => `
                <a href="player.html?id=${video.id}" class="video-card">
                    <div class="video-thumbnail">
                        <i>🎬</i>
                        <div class="video-duration">${video.duration || '00:00'}</div>
                    </div>
                    <div class="video-info">
                        <h3 class="video-title">${video.title}</h3>
                        <div class="video-meta">${video.uploaderName || '未知老师'}</div>
                        <div class="video-meta">${Utils.formatTime(video.uploadTime)}</div>
                        <div class="video-stats">
                            <span class="video-views">${video.views || 0} 次观看</span>
                            <button class="favorite-btn" onclick="toggleFavorite(event, ${video.id})" title="收藏">
                                ❤️
                            </button>
                        </div>
                    </div>
                </a>
            `).join('');
        }

        // 显示空状态
        function showEmptyState(message) {
            const container = document.getElementById('videosGrid');
            container.innerHTML = `
                <div class="empty-state" style="grid-column: 1 / -1;">
                    <i>🎥</i>
                    <p>${message}</p>
                </div>
            `;
        }

        // 切换收藏状态
        function toggleFavorite(event, videoId) {
            event.preventDefault();
            event.stopPropagation();
            
            const btn = event.target;
            const isFavorited = btn.classList.contains('favorited');
            
            if (isFavorited) {
                btn.classList.remove('favorited');
                Message.info('已取消收藏');
            } else {
                btn.classList.add('favorited');
                Message.success('已添加到收藏');
            }
            
            // 这里可以调用API来保存收藏状态
        }

        // 退出登录
        async function logout() {
            try {
                await API.post('/user/logout');
                sessionStorage.removeItem('user');
                window.location.href = '../login.html';
            } catch (error) {
                console.error('退出登录失败:', error);
                Message.error('退出登录失败');
            }
        }
    </script>
</body>
</html>
